/* eslint-disable no-undef */
/**
 * Created by YongX on 2017/7/1.
 */

import axios from 'axios';

axios.defaults.baseURL = 'http://localhost:8080/api/';
axios.defaults.timeout = 10000;
window.axios = axios;

axios.interceptors.request.use(function (configure) {
    let token = __.$storage.get(__.$key.ACCESS_TOKEN);
    if (token !== null) {
        configure.headers['Authorization'] = 'Bearer ' + (__.$storage.get(__.$key.ACCESS_TOKEN) || '');
    }
    return configure;
}, function (error) {
    return Promise.reject(error);
});

axios.interceptors.response.use((response) => {
    return response;
}, (error) => {
    switch (error.response.status) {
        case 403:
            openNotify('无法获取数据, 未授权操作' + error.response.statusText);
            break;
        case 401:
            openNotify(error.response.statusText);
            __.$storage.clear();
            __.$router.push({name: 'Login'});
            break;
        case 504:
        case 500:
        case 400:
            openNotify('链接失败 [' + error.response.statusText + ']');
            break;
    }
    return Promise.reject(error);
});

function openNotify (mes) {
    __.$notify.open({
        fixed: 'top-right',
        timeout: 5000,
        content: mes,
        type: 'warning'
    });
}
